package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Cart;
import cn.wolfcode.trip.base.domain.Goods;
import cn.wolfcode.trip.base.domain.PointMsg;
import cn.wolfcode.trip.base.mapper.CartMapper;
import cn.wolfcode.trip.base.mapper.GoodsMapper;
import cn.wolfcode.trip.base.mapper.PointMsgMapper;
import cn.wolfcode.trip.base.query.CartQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ICartService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private PointMsgMapper pointMsgMapper;

    public void delete(Long id) {
        cartMapper.deleteByPrimaryKey(id);
    }

    public List<Cart> listUndeterminedCart(Long userId) {
        return cartMapper.selectCartForState(userId, Cart.STATE_UNDETERMINED);
    }

    public void saveOrUpdate(CartQueryObject qo) {
        Cart CartMsg = cartMapper.checkMsg(qo.getUserId(), qo.getGoodsId(), Cart.STATE_UNDETERMINED);
        if ( CartMsg !=null) {
            CartMsg.setCount(CartMsg.getCount()+1);
            cartMapper.updateCountNPrice(CartMsg);
        } else {
            Goods goods = goodsMapper.selectByPrimaryKey(qo.getGoodsId());
            Cart cart = new Cart();
            if (qo.getAddressId()!=null){
                cart.setAddressId(qo.getAddressId());
            }
            if (qo.getState()!=null){
                cart.setState(qo.getState());
            }
            cart.setGoods(goods);
            cart.setUserId(qo.getUserId());
            cart.setAddTime(new Date());
            cartMapper.insert(cart);
        }
    }

    public PageInfo<Cart> listRecord(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Cart> carts = cartMapper.selectList(qo);
        return new PageInfo<>(carts);
    }

    public void updateState(Cart cart) {
        cart.setAddTime(new Date());
        cartMapper.updateState(cart);
    }

    public void savePointMsg(PointMsg pointMsg) {
        pointMsg.setCreateTime(new Date());
        pointMsgMapper.insert(pointMsg);
    }

    public void updateCount(Cart cart) {
        cartMapper.updateCountNPrice(cart);
    }

    public Cart getCart(Long id) {
        Cart cart = cartMapper.selectByPrimaryKey(id);
        return cart;
    }


}
